//
//  WebWithBridgeController.m
//  JsRunOCDemo
//
//  Created by HB on 16/7/4.
//  Copyright © 2016年 Zhangjitao. All rights reserved.
//

#import "WebWithBridgeController.h"
#import "WebViewJavascriptBridge.h"

@interface WebWithBridgeController ()<UIWebViewDelegate>

@property (nonatomic,strong) UIWebView *webView;

@end

@implementation WebWithBridgeController
@synthesize javascriptBridge = _bridge;

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor blueColor];
    
    _webView = [[UIWebView alloc] init];
    _webView.backgroundColor = [UIColor whiteColor];
    _webView.frame = CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height);
    _webView.delegate = self;
    
    NSString *basePath = [[NSBundle mainBundle] bundlePath];
    NSString *helpHtmlPath = [basePath stringByAppendingPathComponent:@"2.html"];
    NSURL *url = [NSURL fileURLWithPath:helpHtmlPath];
    [_webView loadRequest:[NSURLRequest requestWithURL:url]];
    
    [self.view addSubview:_webView];
    
    
    [self createBridge];
    
}

-(void)createBridge
{
    /*
     * 默认必须写的，JS调用OC，返回一个参数 data
     * 如果不想返回参数 则将handler的参数制成null
     */
    
    _bridge = [WebViewJavascriptBridge bridgeForWebView:_webView handler:^(id data, WVJBResponseCallback responseCallback) {
        //返回的参数在这里进行OC的代码编写
        NSLog(@"ObjC received message from JS one----: %@", data);
        responseCallback(@"Response for message from ObjC");
    }];
    
    /*
     *JS调用OC时必须写的，注册一个JS调用OC的方法
     */
    //注册一个供UI端调用的名为testObjcCallback的处理器，并定义用于响应的处理逻辑
    
    [_bridge registerHandler:@"pop" handler:^(id data, WVJBResponseCallback responseCallback) {
        // 分享
        NSLog(@"onShare called tow----: %@", data);
        [self popNav];
        responseCallback(@"Response from testObjcCallback");
    }];

}

- (void)popNav {
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
